const path=require('path')
const glob=require('glob')
//创建html模板
const HtmlWebpackPlugin=require('html-webpack-plugin')
//创建css模板
const OptimizeCSSAssetsPlugin=require('optimize-css-assets-webpack-plugin')
//css压缩
const MiniCssExtractPlugin=require('mini-css-extract-plugin')
// 移除无用css
const PurgecssWebpackPlugin=require('purgecss-webpack-plugin')
module.exports = {
    entry:'./src/main.js',
    // entry: ['@babel/polyfill','./src/index.js'],
    // entry: { // 属性值为一个对象
    //     a: "./src/main.js",
    //     b: "./src/index.js"
    // },
    output: {
        path: path.resolve(__dirname, "./dist"),
        // filename: "bundle.js",
        // filename: "js/[name].js",
        filename: "js/[name][chunkhash:8].js",
        // libraryTarget: "this",
        // libraryTarget: "commonjs",
        // libraryTarget: "commonjs2",
        libraryTarget: "var",
        library: "test"
        // filename: "js/[name][hash:8].js",
    },
    devServer: {
        port: 3000, // 让devServer监听3000端口
        contentBase: "./dist", // 将当前项目的dist目录作为devServer的根目录
        progress: true, // 显示打包进度条
        compress: true // 是否启用Gzip压缩，默认为false
    },

    plugins: [
        new HtmlWebpackPlugin(
            {
                template: "./src/index.html",
                filename: "index.html",
                minify:{
                    removeAttributeQuotes:true,
                    collapseWhitespace:true
                },
                hash: true
            }
        ),
        new MiniCssExtractPlugin(
            {
                filename: "css/[name].[contenthash:8].css",
            }
        ),
        new PurgecssWebpackPlugin(
            {
                // paths:['./src/index,html']
                paths: glob.sync(`./src/**/*`, { // 即同步搜索，匹配public目录下所有的文件，返回一个包含所有匹配到文件的数组
                    nodir: true // 不包含目录
                })
            }
        )
    ],
    optimization:{
        minimize:true,
        minimizer: [
            // 压缩
            new OptimizeCSSAssetsPlugin(
                {
                    assetNameRegExp: /\.css$/g,
                    cssProcessor: require('cssnano'),
                    cssProcessorPluginOptions: {
                        preset: ['default', { discardComments: { removeAll: true } }],
                    },
                    canPrint: true
                }
            )
        ]
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    // "style-loader",

                    "css-loader",
                    "postcss-loader",//添加前缀

                ]
            },
            {
                test: /\.js$/,
                use: [
                    "babel-loader"

                ]
            }
        ]
    },
}